<template>
  <div class="label-template-form">
    <n-card :bordered="false" class="proCard">
      <div class="label-template-form-item-list">
        <div class="label-template-form-item">
          <div class="label-template-form-item-title">
            {{ t('labelTemplate.form.basicInfoTitle') }}
          </div>
          <DFForm
            ref="basicFormRef"
            route-name="labelTemplate"
            label-width="112px"
            class="basicForm"
            @register="modalFormRegister"
          />
        </div>
        <div class="label-template-form-item descInfoTable">
          <div class="label-template-form-item-title">
            {{ t('labelTemplate.form.descInfoTitle') }}
          </div>
          <DFTable
            ref="descInfoRef"
            route-name="labelTemplate"
            has-selection
            no-default-load
            :columns="descInfoColumns"
            :row-key="(row: descriptiveInformationObj) => row.index"
            :has-index="false"
            :action-column="descInfoActionColumn"
            :opera-column="descInfoOperaColumn"
            :checked-row-keys="descInfoMultipleSelection"
            :checked-row-key-model="true"
            :on-update:checked-row-keys="changeDescInfoSelectionFn"
            :max-height="240"
          />
        </div>
        <div class="label-template-form-item tableInfoTable">
          <div class="label-template-form-item-title">
            {{ t('labelTemplate.form.tableInfoTitle') }}
          </div>
          <DFTable
            ref="tableInfoRef"
            route-name="labelTemplate"
            has-selection
            no-default-load
            :columns="tableInfoColumns"
            :row-key="(row: tableInformationObj) => row.index"
            :has-index="false"
            :action-column="tableInfoActionColumn"
            :opera-column="tableInfoOperaColumn"
            :checked-row-keys="tableInfoMultipleSelection"
            :checked-row-key-model="true"
            :on-update:checked-row-keys="changeTableInfoSelectionFn"
            :max-height="240"
          />
        </div>
      </div>
      <div class="basicInfo-bottom defaultButtonClass">
        <div>
          <n-button class="add-btn" @click="handleBackFn">
            {{ $t('common.button.back') }}
          </n-button>
          <n-button type="primary" class="add-btn" @click="handleSubmitFn('preview')">
            {{ $t('common.button.preview') }}
          </n-button>
          <n-button type="primary" :loading="saveLoading" class="add-btn" @click="handleSubmitFn()">
            {{ $t('common.button.save') }}
          </n-button>
        </div>
      </div>
    </n-card>
    <TemplateModal ref="templateModalRef" :temp-info="tempInfo" />
  </div>
</template>

<script lang="ts" setup name="LabelTemplateForm">
  import type { Ref } from 'vue';
  import { h, ref } from 'vue';
  import { NInput, NSelect } from 'naive-ui';
  import { useRoute } from 'vue-router';
  import { cloneDeep } from 'lodash';
  import Sortable from 'sortablejs';
  import TemplateModal from './components/TemplateModal.vue';
  import lang from './lang';
  import { DFForm, useForm } from '@/components/DFForm/index';
  import { DFTable, DFTableAction } from '@/components/DFTable';
  import { useMixins } from '@/hooks/useMixins';
  import { renderSvg } from '@/utils/index';
  import {
    addLabelTemplate,
    infoLabelTemplate,
    updateLabelTemplate,
  } from '@/api/system/labelTemplate';
  import orderLang from '@/views/permission/production/order/lang';
  import { messages, t } from '@/i18n';
  import { cloumsMaterial } from '@render/api/base/material';

  const { loadLangFn, dialogWarningFn, toBackFn, message, router } = useMixins();
  loadLangFn(lang);

  const route = useRoute();
  const { id, pageType } = toRaw(route)?.query || {};

  const basicFormRef: any = ref(null);
  const descInfoRef: any = ref(null);
  const tableInfoRef: any = ref(null);
  const descInfoMultipleSelection = ref([]);
  const descInfoDelBtnDisabled = ref(true);
  const tableInfoMultipleSelection = ref([]);
  const tableInfoDelBtnDisabled = ref(true);
  const saveLoading = ref(false);
  const templateModalRef: any = ref(null);

  interface descriptiveInformationObj {
    id?: number;
    index: number;
    columnName: string | null;
    columnDetailZh: string | null;
    columnDetailEn: string | null;
    customNameZh: string | null;
    customNameEn: string | null;
    customValue: string | null;
  }
  interface tableInformationObj {
    id?: number;
    index: number;
    columnName1: string | null;
    columnDetailZh1: string | null;
    columnDetailEn1: string | null;
    customNameZh1: string | null;
    customNameEn1: string | null;
    customValue1: string | null;
    columnName2: string | null;
    columnDetailZh2: string | null;
    columnDetailEn2: string | null;
    customNameZh2: string | null;
    customNameEn2: string | null;
    customValue2: string | null;
  }
  const defaultDescriptiveInformation: descriptiveInformationObj = {
    index: 1,
    columnName: null,
    columnDetailZh: '',
    columnDetailEn: '',
    customNameZh: '',
    customNameEn: '',
    customValue: '',
  };
  const defaultTableInformation: tableInformationObj = {
    index: 1,
    columnName1: null,
    columnDetailZh1: '',
    columnDetailEn1: '',
    customNameZh1: '',
    customNameEn1: '',
    customValue1: '',
    columnName2: null,
    columnDetailZh2: '',
    columnDetailEn2: '',
    customNameZh2: '',
    customNameEn2: '',
    customValue2: '',
  };

  const descriptiveInformationList = ref<descriptiveInformationObj[]>([
    { ...cloneDeep(defaultDescriptiveInformation) },
  ]);
  const tableInformationList = ref<tableInformationObj[]>([
    { ...cloneDeep(defaultTableInformation) },
  ]);

  interface fieldObj {
    columnName: string;
    columnDetailZh: string | null;
    columnDetailEn: string | null;
  }

  let defaultForm: any = {};

  // 表单信息
  const modalFormSchemas: any = [
    {
      field: 'tempName',
      component: 'NInput',
      label: 'templateName',
      defaultValue: '',
      componentProps: {
        disabled: pageType === 'edit',
        maxlength: 100,
        clearable: true,
      },
      rules: [{ required: true, message: t('common.formTipMsg.input'), trigger: ['blur'] }],
    },
    {
      field: 'tempTitleZh',
      component: 'NInput',
      label: 'templateNameZh',
      defaultValue: '',
      componentProps: {
        maxlength: 100,
        clearable: true,
      },
      rules: [{ required: true, message: t('common.formTipMsg.input'), trigger: ['blur'] }],
    },
    {
      field: 'tempTitleEn',
      component: 'NInput',
      label: 'templateNameEn',
      defaultValue: '',
      componentProps: {
        maxlength: 100,
        clearable: true,
      },
      rules: [{ required: true, message: t('common.formTipMsg.input'), trigger: ['blur'] }],
    },
    {
      field: 'tempDetail',
      component: 'NInput',
      label: 'templateDesc',
      defaultValue: '',
      span: 3,
      componentProps: {
        maxlength: 250,
        clearable: true,
      },
    },
  ];

  const [modalFormRegister, { validate, getFieldsValue: getModalFormValFn, setFieldsValue }] =
    useForm({
      gridProps: { cols: 3 },
      collapsedRows: 3,
      labelWidth: 140,
      layout: 'horizontal',
      showActionButtonGroup: false,
      schemas: modalFormSchemas,
    });

  // 获取详情
  async function getDetails() {
    try {
      const res = await infoLabelTemplate({ id });
      const { code, data = {} } = res || {};
      if (code === 200) {
        const { id, tempName, tempDetail, tempInfo } = data;
        const tempInfoObj = JSON.parse(tempInfo);
        const {
          tempTitleZh,
          tempTitleEn,
          descriptiveInformationList: descInfoList,
          tableInformationList: tableInfoList,
        } = tempInfoObj || {};
        await setFieldsValue({
          id,
          tempName,
          tempDetail,
          tempTitleZh,
          tempTitleEn,
        });
        descriptiveInformationList.value = descInfoList;
        tableInformationList.value = tableInfoList;
        descInfoRef.value?.setTableData(descInfoList);
        tableInfoRef.value?.setTableData(tableInfoList);
        defaultForm = {
          id,
          tempName,
          tempDetail,
          tempTitleZh,
          tempTitleEn,
          descriptiveInformationList: [...cloneDeep(descInfoList)],
          tableInformationList: [...cloneDeep(tableInfoList)],
        };
      }
    } catch {}
  }

  const fieldOptions: any = ref([]);

  // 获取产品字段列表方法
  async function getPrintFields() {
    try {
      const res = await cloumsMaterial();
      const { data = [] } = res || {};
      if (data?.length) {
        for (let i = 0; i < data.length; i++) {
          const key = data[i].key;
          if (orderLang.zh.order.table[key]) {
            fieldOptions.value.push({
              columnName: key,
              columnDetailZh: orderLang.zh.order.table[key],
              columnDetailEn: orderLang.en.order.table[key],
            });
            continue;
          }
          if (messages.zh.common.table[key]) {
            fieldOptions.value.push({
              columnName: key,
              columnDetailZh: messages.zh.common.table[key],
              columnDetailEn: messages.en.common.table[key],
            });
          }
        }
      }
      fieldOptions.value.push(
        {
          columnName: 'materialStandards',
          columnDetailZh: '产品规格',
          columnDetailEn: 'Product Spec',
        },
        {
          columnName: 'paperSize',
          columnDetailZh: '纸板规格',
          columnDetailEn: 'Cardboard Spec',
        },
        {
          columnName: 'custom',
          columnDetailZh: '自定义',
          columnDetailEn: 'Customized',
        },
        {
          columnName: 'printTime',
          columnDetailZh: '打印时间',
          columnDetailEn: 'Print Time',
        },
        {
          columnName: 'bundleNum',
          columnDetailZh: '托盘数 / 堆叠数',
          columnDetailEn: 'Bundle Num / QTY',
        }
      );
    } catch {}
  }

  onMounted(async () => {
    // 获取需打印的产品字段列表
    await getPrintFields();

    // 获取详情 赋初始值
    if (pageType === 'edit' || pageType === 'copy') {
      await getDetails();
    } else {
      descInfoRef.value?.setTableData(descriptiveInformationList.value);
      tableInfoRef.value?.setTableData(tableInformationList.value);
      defaultForm = {
        id: null,
        tempName: '',
        tempDetail: '',
        tempTitleZh: '',
        tempTitleEn: '',
        descriptiveInformationList: [{ ...cloneDeep(defaultDescriptiveInformation) }],
        tableInformationList: [{ ...cloneDeep(defaultTableInformation) }],
      };
    }
    // 拖动排序
    await nextTick(() => {
      // 描述信息
      const tbody = document.querySelector(
        `.descInfoTable .n-data-table-base-table-body tbody.n-data-table-tbody`
      );
      new Sortable(tbody, {
        animation: 150,
        handle: '.fixed-modal-sort',
        filter: '.no-draggable',
        invertSwap: false,
        preventOnFilter: true,
        onSort: (/** Event */ _evt) => {},
        onChange: (_e, _a, _c) => {},
        onMove: (/** Event */ _evt, /** Event */ _originalEvent) => {},
        onEnd: async ({ newIndex, oldIndex }) => {
          await getSortBackFn(descriptiveInformationList, oldIndex, newIndex);
          descInfoRef.value?.setTableData(descriptiveInformationList.value);
        },
      });
      // 表格信息
      const tbody1 = document.querySelector(
        `.tableInfoTable .n-data-table-base-table-body tbody.n-data-table-tbody`
      );
      new Sortable(tbody1, {
        animation: 150,
        handle: '.fixed-modal-sort',
        filter: '.no-draggable',
        invertSwap: false,
        preventOnFilter: true,
        onSort: (/** Event */ _evt) => {},
        onChange: (_e, _a, _c) => {},
        onMove: (/** Event */ _evt, /** Event */ _originalEvent) => {},
        onEnd: async ({ newIndex, oldIndex }) => {
          await getSortBackFn(tableInformationList, oldIndex, newIndex);
          tableInfoRef.value?.setTableData(tableInformationList.value);
        },
      });
    });
  });

  async function getSortBackFn(
    list: Ref<(descriptiveInformationObj | tableInformationObj)[]>,
    oldIndex: number,
    newIndex: number
  ) {
    const targetRow = list.value[oldIndex];
    list.value.splice(oldIndex, 1);
    list.value.splice(newIndex, 0, targetRow);
    list.value = list.value.map((item, index) => {
      return {
        ...item,
        index: index + 1,
      };
    });
  }

  // 描述信息
  const descInfoColumns = [
    {
      width: 60,
      type: 'selection',
      key: 'selection',
      fixed: 'left',
    },
    {
      width: 60,
      label: 'order',
      key: 'index',
      fixed: 'left',
      sorter: false,
      common: true,
    },
    {
      label: 'sort',
      common: true,
      sorter: false,
      align: 'center',
      className: 'sort-column',
      render(_row: Recordable) {
        return h(renderSvg('fixedModalSort'), {
          class: 'fixed-modal-sort',
          style: { cursor: 'move' },
        });
      },
    },
    {
      label: 'field',
      key: 'columnName',
      width: 165,
      sorter: false,
      title(column) {
        const title = t(`labelTemplate.form.${column.label}`);
        return h('span', [
          h(
            'span',
            {
              style: {
                color: 'red',
              },
            },
            '* '
          ),
          title,
        ]);
      },
      render(row: descriptiveInformationObj, index: number) {
        return h(NSelect, {
          value: row.columnName,
          options: fieldOptions.value,
          'label-field': 'columnDetailZh',
          'value-field': 'columnName',
          onUpdateValue(v: string, option: fieldObj) {
            const { columnDetailZh = '', columnDetailEn = '' } = option;
            descriptiveInformationList.value[index].columnName = v;
            descriptiveInformationList.value[index].columnDetailZh = columnDetailZh;
            descriptiveInformationList.value[index].columnDetailEn = columnDetailEn;
          },
        });
      },
    },
    {
      label: 'fieldZh',
      key: 'columnDetailZh',
      width: 165,
      sorter: false,
    },
    {
      label: 'fieldEn',
      key: 'columnDetailEn',
      width: 165,
      sorter: false,
    },
    {
      label: 'customNameZh',
      key: 'customNameZh',
      width: 165,
      sorter: false,
      render(row: descriptiveInformationObj, index: number) {
        return h(NInput, {
          value: row.customNameZh,
          maxlength: 100,
          onUpdateValue(v: string) {
            descriptiveInformationList.value[index].customNameZh = v;
          },
        });
      },
    },
    {
      label: 'customNameEn',
      key: 'customNameEn',
      width: 165,
      sorter: false,
      render(row: descriptiveInformationObj, index: number) {
        return h(NInput, {
          value: row.customNameEn,
          maxlength: 100,
          onUpdateValue(v: string) {
            descriptiveInformationList.value[index].customNameEn = v;
          },
        });
      },
    },
    {
      label: 'customValue',
      key: 'customValue',
      width: 165,
      sorter: false,
      render(row: descriptiveInformationObj, index: number) {
        return h(NInput, {
          value: row.customValue,
          maxlength: 250,
          onUpdateValue(v: string) {
            descriptiveInformationList.value[index].customValue = v;
          },
        });
      },
    },
  ];
  const descInfoActionColumn = reactive({
    width: 60,
    widthEn: 80,
    label: 'operation',
    key: 'action',
    fixed: 'right',
    common: true,
    render(record: Recordable) {
      const recordRow = toRaw(record);
      return h(DFTableAction as any, {
        style: 'button',
        actions: [
          {
            type: 'primary',
            label: 'delete',
            onClick: () => {
              const { index } = recordRow;
              dialogWarningFn({}, async () => {
                await handleDeleteRowFn(
                  descriptiveInformationList,
                  toRef([index]),
                  descInfoRef,
                  descInfoMultipleSelection
                );
              });
            },
          },
        ],
      });
    },
  });
  const descInfoOperaColumn = reactive([
    {
      label: 'add',
      bind: {
        type: 'primary',
        onClick: async () => {
          await handleAddRowFn(
            descriptiveInformationList,
            defaultDescriptiveInformation,
            descInfoRef
          );
        },
      },
    },
    {
      label: 'copy',
      bind: {
        type: 'primary',
        disabled: descInfoDelBtnDisabled,
        onClick: async () => {
          await handleCopyRowFn(descriptiveInformationList, descInfoMultipleSelection, descInfoRef);
        },
      },
    },
    {
      label: 'delete',
      bind: {
        disabled: descInfoDelBtnDisabled,
        onClick: async () => {
          await handleDeleteRowFn(
            descriptiveInformationList,
            descInfoMultipleSelection,
            descInfoRef
          );
        },
      },
    },
  ]);

  // 表格信息
  const tableInfoColumns = [
    {
      width: 60,
      type: 'selection',
      key: 'selection',
      fixed: 'left',
    },
    {
      width: 60,
      label: 'order',
      key: 'index',
      fixed: 'left',
      sorter: false,
      common: true,
    },
    {
      label: 'sort',
      common: true,
      sorter: false,
      align: 'center',
      className: 'sort-column',
      render(_row: Recordable) {
        return h(renderSvg('fixedModalSort'), {
          class: 'fixed-modal-sort',
          style: { cursor: 'move' },
        });
      },
    },
    {
      label: 'field1',
      key: 'columnName1',
      width: 165,
      sorter: false,
      title(column) {
        const title = t(`labelTemplate.form.${column.label}`);
        return h('span', [
          h(
            'span',
            {
              style: {
                color: 'red',
              },
            },
            '* '
          ),
          title,
        ]);
      },
      render(row: tableInformationObj, index: number) {
        return h(NSelect, {
          value: row.columnName1,
          options: fieldOptions.value,
          'label-field': 'columnDetailZh',
          'value-field': 'columnName',
          onUpdateValue(v: string, option: fieldObj) {
            const { columnDetailZh = '', columnDetailEn = '' } = option;
            tableInformationList.value[index].columnName1 = v;
            tableInformationList.value[index].columnDetailZh1 = columnDetailZh;
            tableInformationList.value[index].columnDetailEn1 = columnDetailEn;
          },
        });
      },
    },
    {
      label: 'fieldZh1',
      key: 'columnDetailZh1',
      width: 165,
      sorter: false,
    },
    {
      label: 'fieldEn1',
      key: 'columnDetailEn1',
      width: 165,
      sorter: false,
    },
    {
      label: 'customNameZh1',
      key: 'customNameZh1',
      width: 165,
      sorter: false,
      render(row: tableInformationObj, index: number) {
        return h(NInput, {
          value: row.customNameZh1,
          maxlength: 100,
          onUpdateValue(v: string) {
            tableInformationList.value[index].customNameZh1 = v;
          },
        });
      },
    },
    {
      label: 'customNameEn1',
      key: 'customNameEn1',
      width: 165,
      sorter: false,
      render(row: tableInformationObj, index: number) {
        return h(NInput, {
          value: row.customNameEn1,
          maxlength: 100,
          onUpdateValue(v: string) {
            tableInformationList.value[index].customNameEn1 = v;
          },
        });
      },
    },
    {
      label: 'customValue1',
      key: 'customValue1',
      width: 165,
      sorter: false,
      render(row: tableInformationObj, index: number) {
        return h(NInput, {
          value: row.customValue1,
          maxlength: 250,
          onUpdateValue(v: string) {
            tableInformationList.value[index].customValue1 = v;
          },
        });
      },
    },
    {
      label: 'field2',
      key: 'columnName2',
      width: 165,
      sorter: false,
      render(row: tableInformationObj, index: number) {
        return h(NSelect, {
          value: row.columnName2,
          options: fieldOptions.value,
          'label-field': 'columnDetailZh',
          'value-field': 'columnName',
          onUpdateValue(v: string, option: fieldObj) {
            const { columnDetailZh = '', columnDetailEn = '' } = option;
            tableInformationList.value[index].columnName2 = v;
            tableInformationList.value[index].columnDetailZh2 = columnDetailZh;
            tableInformationList.value[index].columnDetailEn2 = columnDetailEn;
          },
        });
      },
    },
    {
      label: 'fieldZh2',
      key: 'columnDetailZh2',
      width: 165,
      sorter: false,
    },
    {
      label: 'fieldEn2',
      key: 'columnDetailEn2',
      width: 165,
      sorter: false,
    },
    {
      label: 'customNameZh2',
      key: 'customNameZh2',
      width: 165,
      sorter: false,
      render(row: tableInformationObj, index: number) {
        return h(NInput, {
          value: row.customNameZh2,
          maxlength: 100,
          onUpdateValue(v: string) {
            tableInformationList.value[index].customNameZh2 = v;
          },
        });
      },
    },
    {
      label: 'customNameEn2',
      key: 'customNameEn2',
      width: 165,
      sorter: false,
      render(row: tableInformationObj, index: number) {
        return h(NInput, {
          value: row.customNameEn2,
          maxlength: 100,
          onUpdateValue(v: string) {
            tableInformationList.value[index].customNameEn2 = v;
          },
        });
      },
    },
    {
      label: 'customValue2',
      key: 'customValue2',
      width: 165,
      sorter: false,
      render(row: tableInformationObj, index: number) {
        return h(NInput, {
          value: row.customValue2,
          maxlength: 250,
          onUpdateValue(v: string) {
            tableInformationList.value[index].customValue2 = v;
          },
        });
      },
    },
  ];
  const tableInfoActionColumn = reactive({
    width: 60,
    widthEn: 80,
    label: 'operation',
    key: 'action',
    fixed: 'right',
    common: true,
    render(record: Recordable) {
      const recordRow = toRaw(record);
      return h(DFTableAction as any, {
        style: 'button',
        actions: [
          {
            type: 'primary',
            label: 'delete',
            onClick: () => {
              const { index } = recordRow;
              dialogWarningFn({}, async () => {
                await handleDeleteRowFn(
                  tableInformationList,
                  toRef([index]),
                  tableInfoRef,
                  tableInfoMultipleSelection
                );
              });
            },
          },
        ],
      });
    },
  });
  const tableInfoOperaColumn = reactive([
    {
      label: 'add',
      bind: {
        type: 'primary',
        onClick: async () => {
          await handleAddRowFn(tableInformationList, defaultTableInformation, tableInfoRef);
        },
      },
    },
    {
      label: 'copy',
      bind: {
        type: 'primary',
        disabled: tableInfoDelBtnDisabled,
        onClick: async () => {
          await handleCopyRowFn(tableInformationList, tableInfoMultipleSelection, tableInfoRef);
        },
      },
    },
    {
      label: 'delete',
      bind: {
        disabled: tableInfoDelBtnDisabled,
        onClick: async () => {
          await handleDeleteRowFn(tableInformationList, tableInfoMultipleSelection, tableInfoRef);
        },
      },
    },
  ]);

  // 新增方法
  async function handleAddRowFn(
    list: Ref<(descriptiveInformationObj | tableInformationObj)[]>,
    defaultObj: descriptiveInformationObj | tableInformationObj,
    tableRef: Ref
  ) {
    list.value.push({
      ...cloneDeep(defaultObj),
      index: list.value.length + 1,
    });
    tableRef.value?.setTableData(list.value);
  }

  // 复制方法
  async function handleCopyRowFn(
    list: Ref<(descriptiveInformationObj | tableInformationObj)[]>,
    selections: Ref<number[]>,
    tableRef: Ref
  ) {
    let copyItem = list.value.filter((item) => selections.value.includes(item.index));
    copyItem = copyItem.map((item, i) => {
      return {
        ...item,
        index: list.value.length + i + 1,
      };
    });
    list.value = list.value.concat(cloneDeep(copyItem));
    tableRef.value?.setTableData(list.value);
  }

  // 删除方法
  async function handleDeleteRowFn(
    list: Ref<(descriptiveInformationObj | tableInformationObj)[]>,
    ids: Ref<number[]>,
    tableRef: Ref,
    selections?: Ref<number[]>
  ) {
    list.value = list.value.filter((item) => !ids.value.includes(item.index));
    list.value = list.value.map((item, index) => {
      return {
        ...item,
        index: index + 1,
      };
    });
    tableRef.value?.setTableData(list.value);
    if (selections) selections.value = selections.value.filter((i) => !ids.value.includes(i));
    else ids.value = [];

    setBtnDisabled();
  }

  // 表格勾选方法
  async function changeDescInfoSelectionFn(rowKeys: number[]) {
    descInfoMultipleSelection.value = rowKeys;
    setBtnDisabled();
  }
  async function changeTableInfoSelectionFn(rowKeys: number[]) {
    tableInfoMultipleSelection.value = rowKeys;
    setBtnDisabled();
  }

  // 按钮置灰
  function setBtnDisabled() {
    descInfoDelBtnDisabled.value = descInfoMultipleSelection.value.length === 0;
    tableInfoDelBtnDisabled.value = tableInfoMultipleSelection.value.length === 0;
  }

  const tempInfo = ref(null);

  async function getFormData() {
    const {
      id = null,
      tempName = '',
      tempDetail = '',
      tempTitleZh = '',
      tempTitleEn = '',
    } = getModalFormValFn();
    return {
      id,
      tempName,
      tempDetail,
      tempTitleZh,
      tempTitleEn,
      descriptiveInformationList: toRaw(descriptiveInformationList.value),
      tableInformationList: toRaw(tableInformationList.value),
    };
  }

  // 返回方法
  async function handleBackFn() {
    const form = await getFormData();
    await toBackFn(null, route, form, defaultForm);
  }

  // 提交方法
  async function handleSubmitFn(type?: 'preview') {
    const errors = await validate();
    if (!errors) {
      let isSubmit = true;
      if (descriptiveInformationList.value?.length) {
        isSubmit = descriptiveInformationList.value.every((item) => {
          if (!item.columnName) {
            message.error(
              t('labelTemplate.tipsMsg.descriptiveInformationError').replace('XXX', item.index)
            );
            return false;
          }
          return true;
        });
      }
      if (tableInformationList.value?.length) {
        isSubmit = tableInformationList.value.every((item) => {
          if (!item.columnName1) {
            message.error(
              t('labelTemplate.tipsMsg.tableInformationError').replace('XXX', item.index)
            );
            return false;
          }
          return true;
        });
      }
      if (isSubmit) {
        const {
          id = null,
          tempName = '',
          tempDetail = '',
          tempTitleZh = '',
          tempTitleEn = '',
          descriptiveInformationList = [],
          tableInformationList = [],
        } = await getFormData();

        const tempInfoTemp = {
          tempTitleZh,
          tempTitleEn,
          descriptiveInformationList,
          tableInformationList,
        };
        // 预览
        if (type) {
          templateModalRef.value?.openModal();
          tempInfo.value = tempInfoTemp;
          return;
        }
        // 保存
        saveLoading.value = true;
        const fn = pageType === 'edit' ? updateLabelTemplate : addLabelTemplate;
        const idTem = pageType === 'edit' ? id : undefined;
        try {
          const res = await fn({
            id: idTem,
            tempName,
            tempDetail,
            tempInfo: JSON.stringify(tempInfoTemp),
          });
          const { code } = res || {};
          if (code === 200) {
            message.success(t('common.tipMsg.saveSuccess'));
            saveLoading.value = false;
            router.go(-1);
          }
        } catch {
          saveLoading.value = false;
        }
      }
    }
  }
</script>

<style lang="less" scoped>
  .label-template-form {
    &-item {
      padding-bottom: 24px;

      &:last-child {
        padding-bottom: 0;
      }

      &-title {
        font-size: 16px;
        font-weight: bold;
        line-height: 1.5;
        padding-bottom: 16px;
      }
    }
  }
</style>
